package com.xiashitech.agent.service.facade;

import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.service.ServiceRegister;
import com.xiashitech.agent.utils.JsonUtil;
import com.xiashitech.interfaces.agent.dto.AgentConfigDTO;

import java.util.function.Consumer;

/**
 * agent客户端门面
 */
public class XSClientFacade {

    private static ServiceRegister<XSClient> register = new ServiceRegister<>(XSClient.class);

    private static XSClient currentService;

    public static void syncConfig(){
        Consumer<String> respHandler = response ->
                AgentConfigDTO.setConfig(JsonUtil.convertStringToObject(response, AgentConfigDTO.class));

        String resp = currentService.syncConfig(respHandler);
        if(checkResponse(resp))
            respHandler.accept(resp);
    }



    private static boolean checkResponse(String response) {
        return response != null && !response.isEmpty() && JsonUtil.isJson(response);
    }


    public static void init() {
        HttpClient httpClient = register.regService(HttpClient.class);
        httpClient.setAgentService(StartConfig.getParamValueFromKey(StartConfig.agentService));

        register.regService(GrpcClient.class);

        currentService = use();
    }

    private static XSClient use() {
        if(StartConfig.isStartGrpc())
            return register.getService(GrpcClient.class);
        else
            return register.getService(HttpClient.class);
    }

}
